package com.cait.dutyfree.security;

import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cait.dutyfree.dataaccess.InventoryServiceDAO;

/**
 * Application Lifecycle Listener implementation class heartBeat
 * 
 * @author Rasika Kaluwalgoda
 * 
 */
public class heartBeat implements ServletContextListener {

	private InventoryServiceDAO inventoryServiceDAO;

	/**
	 * @see ServletContextListener#contextInitialized(ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent arg0) {
		Timer timer = new Timer();
		arg0.getServletContext().setAttribute("hb", timer);

		ServletContext servletContext = arg0.getServletContext();
		final ApplicationContext appContext = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);

		timer.schedule(new TimerTask() {
			public void run() {
				try {
					setInventoryServiceDAO((InventoryServiceDAO) appContext
							.getBean("inventoryServiceDAO"));
					System.out.println("Heart beat...");
					System.out
							.println(getInventoryServiceDAO().getCurrencies());
				} catch (Exception ex) {
					System.out.println("ERR!!!! " + ex);
				}
			}
		}, 1, 1000 * 60 * 60 * 1);

	}

	/**
	 * @see ServletContextListener#contextDestroyed(ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		Timer t = (Timer) arg0.getServletContext().getAttribute("hb");
		t.cancel();
	}

	/**
	 * @return the inventoryServiceDAO
	 */
	public InventoryServiceDAO getInventoryServiceDAO() {
		return inventoryServiceDAO;
	}

	/**
	 * @param inventoryServiceDAO
	 *            the inventoryServiceDAO to set
	 */
	public void setInventoryServiceDAO(InventoryServiceDAO inventoryServiceDAO) {
		this.inventoryServiceDAO = inventoryServiceDAO;
	}

}
